<template>
  <div class="xtx-city">
    <div class="select" @click="toggleDialog" :class="{ active: active }">
      <span class="placeholder" v-if="!changeResult.resultAddress"
        >请选择配送地址</span
      >
      <span v-else class="value">{{ changeResult.resultAddress }}</span>
      <span class="value"></span>

      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="active">
      <span
        class="ellipsis"
        v-for="item in dataList"
        :key="item.code"
        @click="handleItemClick(item)"
        >{{ item.name }}</span
      >
    </div>
  </div>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import axios from 'axios'
export default {
  name: 'XtxCity',
  // 将 context 中的emit 解构出来
  // 这里练习watch语法一下
  setup (props, { emit }) {
    // 现因功能
    const active = ref(false)
    const open = () => {
      active.value = true
    }
    const close = () => {
      active.value = false
    }
    const toggleDialog = () => {
      if (active.value) {
        close()
      } else {
        open()
      }
    }
    // 获取 省市区 数据
    const dataList = ref([])
    let cacheListJSON = ''
    const loadCityList = async () => {
      const res = await axios({
        method: 'get',
        url: 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
      })
      console.log(res)
      dataList.value = res.data

      // 深拷贝
      cacheListJSON = JSON.stringify(res.data)
    }
    loadCityList()
    const changeResult = reactive({
      provinceCode: '', // 省code
      provinceName: '', // 省名称
      cityCode: '', // 城市code
      cityName: '', // 城市名称
      countyCode: '', // 地区code
      countyName: '', // 地区名
      resultAddress: '' // 最终结果地址
    })
    const handleItemClick = (item) => {
      console.log('item', item)
      // 省级
      if (item.level === 0) {
        changeResult.provinceCode = item.code
        changeResult.provinceName = item.name
      }
      // 市区
      if (item.level === 1) {
        changeResult.cityCode = item.code
        changeResult.cityName = item.name
      }
      if (item.level === 2) {
        changeResult.countyCode = item.code
        changeResult.countyName = item.name
        changeResult.resultAddress = changeResult.provinceName + '-' + changeResult.cityName + '-' + changeResult.countyName

        // 当弹窗关闭的时候 数据也就塞满了，确定选择之后把我们的数据传出去
        // 外面用到city 组件的时候，使用@change=‘回调函数（形参）’ 形参=changeresult
        emit('change', changeResult)
        close()
      }
      dataList.value = item.areaList
    }
    watch(active, (newnal) => {
      if (newnal) {
        dataList.value = JSON.parse(cacheListJSON)
      }
    })

    return {
      changeResult,
      handleItemClick,
      dataList,
      active,
      toggleDialog
    }
  }
}
</script>

<style>
</style>
